using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseWrite.API.Applications.Commands.Departments;
using MediatR;

namespace ContentmanagementBaseWrite.API.Applications.Commandhandlters.Departments
{
    /// <summary>
    /// 更新科室命令处理器
    /// </summary>
    public class UpdateDepartmentCommandHandler : IRequestHandler<UpdateDepartmentCommand, ApiResult<int>>
    {
        /// <summary>
        /// 科室仓储
        /// </summary>
        private readonly IBaseRepository<DepartmentManagementModel> _departmentRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<UpdateDepartmentCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository">科室仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public UpdateDepartmentCommandHandler(IBaseRepository<DepartmentManagementModel> departmentRepository, IMapper mapper, ILogger<UpdateDepartmentCommandHandler> logger)
        {
            _departmentRepository = departmentRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理更新科室命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(UpdateDepartmentCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理科室更新命令，科室ID：{Id}，科室名称：{DepartmentName}", request.Id, request.DepartmentName);

                // 验证科室是否存在
                var existingDepartment =  _departmentRepository.GetAll().FirstOrDefault(x=>x.Id==request.Id);
                if (existingDepartment == null)
                {
                    _logger.LogWarning("科室不存在，ID：{Id}", request.Id);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "科室不存在！",
                        data = 0
                    };
                }

                // 验证科室名称是否与其他科室重复（排除自身）
                var existingDepartments = _departmentRepository.GetAll()
                    .Where(x => x.DepartmentName == request.DepartmentName && x.Id != request.Id);
                
                if (existingDepartments.Any())
                {
                    _logger.LogWarning("科室名称已存在，名称：{DepartmentName}", request.DepartmentName);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.error,
                        message = "科室名称已存在！",
                        data = 0
                    };
                }

                _logger.LogDebug("科室验证通过，开始更新科室信息");

                // 更新科室信息
                existingDepartment.DepartmentName = request.DepartmentName;
                existingDepartment.DepartmentGrade = request.DepartmentGrade;
                existingDepartment.DepartmentStatus = request.DepartmentStatus;
                existingDepartment.DepartmentRemarks = request.DepartmentRemarks;
                existingDepartment.ParentId = request.ParentId;
                existingDepartment.UpdatedTime = DateTime.Now;
                existingDepartment.UpdatedBy = 1; // 这里应该从当前用户上下文获取

                _logger.LogDebug("科室信息更新完成，准备保存到数据库");

                // 保存到数据库
                var result = await _departmentRepository.UpdateAsync(existingDepartment);
                _logger.LogInformation("数据库更新完成，影响行数：{Result}", result);

                if (result > 0)
                {
                    _logger.LogInformation("科室更新成功，ID：{Id}", request.Id);
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.Ok,
                        message = "科室更新成功",
                        data = request.Id
                    };
                }
                else
                {
                    _logger.LogWarning("科室更新失败，数据库未返回影响行数");
                    return new ApiResult<int>
                    {
                        code = ResultEnumCode.fails,
                        message = "科室更新失败",
                        data = 0
                    };
                }

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "科室更新过程中发生异常，科室ID：{Id}", request.Id);
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"科室更新异常：{ex.Message}",
                    data = 0
                };
            }
        }
    }
} 